from .handler_base import HandlerBase
import time
import struct
import platform
from app.utils.config_loader import app_config
from app.utils.logger import ETCLogger

# 初始化日志记录器
logger = ETCLogger()

class GetElectricalHandler(HandlerBase):
    def handle(self, command):
        """
        处理 get_electrical 指令
        :param command: 指令字典
        :return: 响应字典
        """
        logger.info("Executing get_electrical command")

        # 获取 INA 设备的串口端口
        os_type = "windows" if platform.system() == "Windows" else "linux"
        ina_port = app_config.get(f"serial_ports.{os_type}.INA")

        # 发送 Hex 字节：AA0102FFFFFF
        hex_data = bytes.fromhex("AA0102FFFFFF")
        if not self.serial_manager.send_data(ina_port, hex_data):
            logger.error("Failed to send command to INA device")
            return {
                "cmd": "GET_ELECTRICAL",
                "status": "error",
                "message": "Failed to send command",
                "timestamp": int(time.time()),
                "timeout": 1
            }

        # 读取返回数据
        response_data = self.serial_manager.read_data(ina_port, timeout=1)
        if not response_data:
            logger.error("Failed to read data from INA device")
            return {
                "cmd": "GET_ELECTRICAL",
                "status": "error",
                "message": "Failed to read data",
                "timestamp": int(time.time()),
                "timeout": 1
            }

        # 解析返回数据（假设返回格式为 4 个浮点数，每个占 4 字节）
        try:
            values = struct.unpack('4f', response_data)  # 解析为 4 个浮点数
            v1, v2, i1, i2 = values
            logger.info(f"Received data from INA device: V1={v1}, V2={v2}, I1={i1}, I2={i2}")
            return {
                "cmd": "GET_ELECTRICAL",
                "status": "success",
                "data": {
                    "V1": v1,
                    "V2": v2,
                    "I1": i1,
                    "I2": i2
                },
                "timestamp": int(time.time()),
                "timeout": 1
            }
        except Exception as e:
            logger.error(f"Failed to parse data from INA device: {e}")
            return {
                "cmd": "GET_ELECTRICAL",
                "status": "error",
                "message": "Failed to parse data",
                "timestamp": int(time.time()),
                "timeout": 1
            }